//
//  registViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-4-2.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "registViewController.h"
#import "LoginController.h"
#import "PartiesEntity.h"
#import "Utils.h"
#import "RegisterServiceViewController.h"

@interface registViewController ()<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>{
    UILabel *partyField,*unitField,*jobField,*branchField;
    UILabel* curPickField;
    
    NSArray *partyDataSource,*unitDataSource,*jobDataSource,*branchDataSource;
    
    UIPickerView *picker;
    
    NSArray *pickerDataSourceArray;
    
    NSLayoutConstraint *pickerBottomConstraint,*pickerLeftConstraint;
    
    UIButton *registButton;
    
    NSArray *unitInfoArray,*branchInfoArray;
    
    
    BOOL jobSelect,unitSelect,insitituSelect,branchEnable;
    UIButton * _isReadBtn;
    UIButton * _serviceBtn;
    
    UITextField *_nickname;
    UITextField *_email;
    UITextField *_identifyNo;
    
    BOOL isSuccess;
    
    UIScrollView * _scrollView;
}

@property (nonatomic,assign) BOOL     isRead;
@property (nonatomic,strong) UIView * bcgView ;
@property (nonatomic,strong) UIView * windowView;

@end

@implementation registViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

-(id)initWithLabelTextArray:(NSArray *)array{
    self = [super initWithLabelTextArray:array];
    if (self){
        jobSelect=NO;
        unitSelect=NO;
        insitituSelect=NO;
    

        NSArray *placeHolderArray = @[@"请输入昵称",@"请输入您的邮箱",@"输入身份证号",@"点击选择党委",@"点击选择单位"
                                      ,@"点击选择职位",@"点击选择支部",@"请输入密码",@"请确认密码"];
        for (NSInteger i=0;i<self.TextFieldArray.count;i++){
            if (i>=3&&i<=6){
                UILabel *textField = self.TextFieldArray[i];
                textField.font = [UIFont systemFontOfSize:14.0f];
                textField.text=placeHolderArray[i];
                textField.textColor = [UIColor colorWithRed:201.0f/255 green:201.0f/255.0f blue:207.0f/255.0f alpha:1.0f];
//                [_scrollView addSubview:textField];
            }
            else {
                UITextField *textField = self.TextFieldArray[i];
                textField.placeholder=placeHolderArray[i];
                textField.font = [UIFont systemFontOfSize:14.0f];
                [textField setDelegate:self];
//                [_scrollView addSubview:textField];
            }
        }
        
        partyField = self.TextFieldArray[3];
        unitField = self.TextFieldArray[4];
        jobField = self.TextFieldArray[5];
        branchField=self.TextFieldArray[6];

        
        
        UITapGestureRecognizer *touchRecognizer  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureForSomeTextField:)];
        [partyField addGestureRecognizer:touchRecognizer];
        
        
        UITapGestureRecognizer *touchRecognizer1  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureForUnitField:)];
        
        [unitField addGestureRecognizer:touchRecognizer1];
        
        UITapGestureRecognizer *touchRecognizer2  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureForJobField:)];
        
        [jobField addGestureRecognizer:touchRecognizer2];
        
        UITapGestureRecognizer *touchRecognizer3  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureForBranchField:)];
        
        [branchField addGestureRecognizer:touchRecognizer3];
        
        [partyField setUserInteractionEnabled:YES];
        [unitField setUserInteractionEnabled:YES];
        [jobField setUserInteractionEnabled:YES];
        [branchField setUserInteractionEnabled:YES];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    /*
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    //设置滑动方向，下面以此类推
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    */
    
#pragma mark 获取党委列表
    
    NSDictionary *requestData=@{@"type":@"getInstitute"};
    [NetworkCenter AFRequestWithData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSArray *content1= [arr[0] objectForKey:@"content1"];

        unitInfoArray =content1;
        
        NSMutableArray *mut = [[NSMutableArray alloc]init];
        for (NSDictionary *dic in content1){
            [mut addObject:dic[@"partyName"]];
        }
        unitDataSource=[[NSArray alloc]initWithArray:mut];
        isSuccess = YES;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        isSuccess = NO;
    }];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ScreenTouch)];
    [self.bcgView addGestureRecognizer:tapGesture];
    [self.view addGestureRecognizer:tapGesture];

	// Do any additional setup after loading the view.
}

//这个是协议回调，所以需要遵循 UIGestureRecognizerDelegate协议
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

    if (recognizer.direction==UISwipeGestureRecognizerDirectionDown) {
        inputRectTopConstraint.constant=8;
        //执行程序
    }
    if (recognizer.direction==UISwipeGestureRecognizerDirectionUp) {
        if([[UIScreen mainScreen] bounds].size.height>480){
            return;
        }
        inputRectTopConstraint.constant=-120;
        [welcomeLabel setAlpha:0];
        //执行程序
    }
    if (recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        //执行程序
    }
    if (recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        //执行程序
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    _isRead = YES;
    registButton =[[UIButton alloc]init];
    [self.view addSubview:registButton];
    [registButton setTitle:@"提交注册信息" forState:UIControlStateNormal];
    [registButton setBackgroundColor:kNavigationBarColor];
    [registButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registButton.layer setCornerRadius:5];
    [registButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [registButton setHighlighted:YES];
    [registButton addTarget:self action:@selector(registButton:) forControlEvents:UIControlEventTouchUpInside];
    [registButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:registButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.inputRect attribute:NSLayoutAttributeBottom multiplier:1 constant:32]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:registButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.inputRect attribute:NSLayoutAttributeLeft multiplier:1 constant:12]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:registButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.inputRect attribute:NSLayoutAttributeRight multiplier:1 constant:-12]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[registButton(==28)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(registButton)]];
    
    /************************************************************/
    UIButton *isReadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:isReadBtn];
    [isReadBtn setImage:[UIImage imageNamed:@"agree.png"] forState:UIControlStateNormal];
    [isReadBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    isReadBtn.tag = Tag_isReadButton;
    _isReadBtn = isReadBtn;
    
    [isReadBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:isReadBtn
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.inputRect
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:6]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:isReadBtn
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.inputRect
                                                          attribute:NSLayoutAttributeLeft
                                                         multiplier:1 constant:10]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[isReadBtn(==25)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(isReadBtn)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[isReadBtn(==25)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(isReadBtn)]];
    /************************************************************/
    UILabel * label1 = [[UILabel alloc] init];
    [self.view addSubview:label1];
    label1.font = [UIFont systemFontOfSize:10.f];
    label1.text = @"我已阅读并同意";
    label1.textColor =[UIColor blackColor];
    label1.backgroundColor = [UIColor clearColor];
    label1.textAlignment = NSTextAlignmentLeft;
    [label1 setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label1
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.inputRect
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:8]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label1
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:isReadBtn
                                                          attribute:NSLayoutAttributeRight
                                                         multiplier:1 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1(==70)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label1)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label1(==21)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label1)]];
    /************************************************************/
    UIButton *servicesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:servicesBtn];
    [servicesBtn setTitle:@"<成电先锋用户注册协议>" forState:UIControlStateNormal];
    [servicesBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    servicesBtn.titleLabel.font = [UIFont systemFontOfSize:10.f];
    [servicesBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [servicesBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    servicesBtn.tag = Tag_servicesButton;
    _serviceBtn = servicesBtn;
    [servicesBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:servicesBtn
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.inputRect
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:8]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:servicesBtn
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:label1
                                                          attribute:NSLayoutAttributeRight
                                                         multiplier:1 constant:0]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[servicesBtn(==120)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(servicesBtn)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[servicesBtn(==21)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(servicesBtn)]];
    /************************************************************/
    UIButton *backLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:backLoginBtn];
    [backLoginBtn setTitle:@"已有账号?马上登录!" forState:UIControlStateNormal];
    [backLoginBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    backLoginBtn.titleLabel.font = [UIFont systemFontOfSize:10.f];
//    [backLoginBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [backLoginBtn addTarget:self action:@selector(backLoginBtned:) forControlEvents:UIControlEventTouchUpInside];
    
    [backLoginBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backLoginBtn
                                                          attribute:NSLayoutAttributeTop
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:registButton
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:4]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backLoginBtn
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.inputRect
                                                          attribute:NSLayoutAttributeLeft
                                                         multiplier:1 constant:12]];
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:backLoginBtn
//                                                          attribute:NSLayoutAttributeRight
//                                                          relatedBy:NSLayoutRelationEqual
//                                                             toItem:self.inputRect
//                                                          attribute:NSLayoutAttributeRight
//                                                         multiplier:1 constant:-12]];
    

    /***********************************************************/
//    CGFloat y = (self.view.frame.size.height - 180)/2;
//    CGFloat x = (self.view.frame.size.width - 100)/2;
//    [_bcgView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bcgView
//                                                          attribute:NSLayoutAttributeTop
//                                                          relatedBy:NSLayoutRelationEqual
//                                                             toItem:self.view
//                                                          attribute:NSLayoutAttributeBottom
//                                                         multiplier:1 constant:y]];
//    
//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bcgView
//                                                          attribute:NSLayoutAttributeLeft
//                                                          relatedBy:NSLayoutRelationEqual
//                                                             toItem:self.view
//                                                          attribute:NSLayoutAttributeRight
//                                                         multiplier:1 constant:x]];
//
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1(==70)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(_bcgView)]];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label1(==21)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(_bcgView)]];
    
    
    
    
    
    /************************************************************/

    self.bcgView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.bcgView setAlpha:0.5];
    [self.bcgView setBackgroundColor:[UIColor blackColor]];
//    [self.view addSubview:self.bcgView];
//    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;   // 获得根窗口
//    [keyWindow addSubview:self.bcgView];
  
    CGFloat y = (self.view.frame.size.height - 120)/2;
    CGFloat x = (self.view.frame.size.width - 260)/2;
    //加入pickerView
    picker = [[UIPickerView alloc]initWithFrame:CGRectMake( x, y, 260, 120)];
//    [self.view addSubview:picker];
//    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;   // 获得根窗口
//    [keyWindow addSubview:picker];
//    [picker setBackgroundColor:[UIColor blackColor]];
    picker.delegate=self;
    picker.dataSource=self;
    
    [picker setBackgroundColor:[UIColor whiteColor]];
    [picker setAlpha:0.8];
    picker.showsSelectionIndicator=YES;
    picker.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth; //这里设置了就可以自定                                                                                                                           义高度了，一般默认是无法修改其216像素的高度
    /*
    [picker setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[picker]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(picker)]];
    
    
//    CGFloat y = (self.view.frame.size.height - 180)/2;
//    CGFloat x = (self.view.frame.size.width - 100)/2;
    
    pickerBottomConstraint=[NSLayoutConstraint constraintWithItem:picker attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    
    
//    pickerLeftConstraint = [NSLayoutConstraint constraintWithItem:picker attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
    
    [self hidePicker];
    
    [self.view addConstraint:pickerBottomConstraint];
    */
//    [self.view addConstraint:pickerLeftConstraint];
    
    partyDataSource=@[@"各单位党委"];
    unitDataSource=@[@"22",@"33",@"44"];
    jobDataSource=@[@"本科生",@"研究生",@"博士",@"教师"];
    branchDataSource=@[];
    
#warning text here
    pickerDataSourceArray=@[@"111",@"222",@"333"];
    
    
    UITextField *pas =self.TextFieldArray[7];
    [pas setSecureTextEntry:YES];
    UITextField *pas1 =self.TextFieldArray[8];
    [pas1 setSecureTextEntry:YES];
}
//取得当前程序的委托
-(AppDelegate *)appDelegate{
    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}


-(void)backLoginBtned:(UIButton*)btn{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UIButtonClicked Method
- (void)buttonClicked:(id)sender{
    UIButton *btn = (UIButton *)sender;
    switch (btn.tag) {
        case Tag_isReadButton:
        {
            //是否阅读协议
            [self setReadBtnImage];
//            if (_isRead) {
//                [Alert showAlert:@"取消同意协议!"];
//                [_isReadBtn setBackgroundColor:[UIColor clearColor]];
//                [_isReadBtn setImage:[UIImage imageNamed:@"disagree.png"] forState:UIControlStateNormal];
//                _isRead = NO;
//            }else{
//                [Alert showAlert:@"同意协议!"];
//                [_isReadBtn setImage:[UIImage imageNamed:@"agree.png"] forState:UIControlStateNormal];
//                _isRead = YES;
//            }
        }
            break;
        case Tag_servicesButton:
        {
            //服务协议
            NSString * filePath = [[NSBundle mainBundle] pathForResource:@"register" ofType:@"txt"];
            NSString * content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
            RegisterServiceViewController * viewController = [[RegisterServiceViewController alloc] initWithContent:content agreeBlock:^{
                _isRead = YES;
//                NSLog(@"回调执行");
//                [_isReadBtn setImage:[UIImage imageNamed:@"agree.png"] forState:UIControlStateNormal];
                [self setReadBtnImage];
            }];
            [self presentViewController:viewController animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
    
}

-(void)setReadBtnImage{
    if (_isRead) {
        [_isReadBtn setImage:[UIImage imageNamed:@"disagree.png"] forState:UIControlStateNormal];
        _isRead = NO;
    }else{
        [_isReadBtn setImage:[UIImage imageNamed:@"agree.png"] forState:UIControlStateNormal];
        _isRead = YES;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    for (id textField in self.TextFieldArray){
        if ([textField isKindOfClass:[UITextField class]])
        [textField resignFirstResponder];
    }
    
    inputRectTopConstraint.constant=8;
    [welcomeLabel setAlpha:1];
[UIView animateWithDuration:0.25 animations:^{
    [self.view layoutIfNeeded];
}];
    [self hidePicker];

}

#pragma mark - textField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [self hidePicker];

//    NSLog(@"%f",textField.viewForBaselineLayout.frame.origin.y);
    NSLog(@"%f",textField.frame.origin.y);
    
//    CGFloat offset = textField.frame.origin.y;
    
//    if (offset>100){
//        if (offset==160)inputRectTopConstraint.constant-=40;
//    }
    
    if (textField.frame.origin.y>100){
        inputRectTopConstraint.constant=-textField.frame.origin.y+100;
        [welcomeLabel setAlpha:0];
    }
    else{
        inputRectTopConstraint.constant=8;
        [welcomeLabel setAlpha:1];
    }
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

-(void)ScreenTouch{
    [self hidePicker];
//    [self.bcgView removeFromSuperview];
}
#pragma  mark - picker delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (curPickField!=branchField)branchEnable=NO;

    
    [curPickField setText:[self pickerView:pickerView titleForRow:row forComponent:component]];
    if (curPickField==jobField){
        [self requestBranchDataSource];
    }

}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
    
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
     return pickerDataSourceArray[row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [pickerDataSourceArray count];
}


-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 40;
}
//
//-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
//    return 320;
//}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    UILabel * myView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 40)];
    myView.font = [UIFont boldSystemFontOfSize:15];
    myView.text = pickerDataSourceArray[row];
    myView.textAlignment = NSTextAlignmentCenter;
//    myView.textColor = [UIColor whiteColor];
    return myView;

}

#pragma mark - 点击选择拦
-(void)tapGestureForSomeTextField:(UITapGestureRecognizer *)recognizer{
    curPickField=partyField;
    pickerDataSourceArray=partyDataSource;
    [picker reloadAllComponents];
    [self showPicker];
    partyField.text=pickerDataSourceArray[[picker selectedRowInComponent:0]];
    insitituSelect=YES;
    
}

//点击党委栏
-(void)tapGestureForUnitField:(UITapGestureRecognizer *)recognizer{

    if (!isSuccess) {
        [Alert showAlert:@"网络请求出错!"];
        return;
    }
    
    if (insitituSelect==NO){
        [Alert showAlert:@"请选择党委"];
        return;
    }
        curPickField=unitField;
    pickerDataSourceArray=unitDataSource;
        [picker reloadAllComponents];
    [self showPicker];
    unitField.text=pickerDataSourceArray[[picker selectedRowInComponent:0]];
    unitSelect=YES;
}

//点击单位栏
-(void)tapGestureForJobField:(UITapGestureRecognizer *)recognizer{
    if (unitSelect==NO){
        [Alert showAlert:@"请选择单位"];
        return;
    }
    if ([[UIScreen mainScreen] bounds].size.height<=548.0f) {
        inputRectTopConstraint.constant=-jobField.frame.origin.y+100;
    }

    [welcomeLabel setAlpha:0];
    curPickField=jobField;
    pickerDataSourceArray=jobDataSource;
    [picker reloadAllComponents];
    [self showPicker];
    jobField.text=pickerDataSourceArray[[picker selectedRowInComponent:0]];
    if (!jobSelect)    [self requestBranchDataSource];
    jobSelect=YES;
    
}


//点击支部栏
-(void)tapGestureForBranchField:(UITapGestureRecognizer *)recognizer{
    if (!branchEnable){
        [Alert showAlert:@"请等待数据"];
        return;
    }
    if (!jobSelect){
        [Alert showAlert:@"请选择职位"];
        return;
    }
    if ([[UIScreen mainScreen] bounds].size.height<=548.0f) {
        inputRectTopConstraint.constant=-jobField.frame.origin.y+100;
    }
    [welcomeLabel setAlpha:0];
        curPickField=branchField;
    pickerDataSourceArray=branchDataSource;
        [picker reloadAllComponents];
    [self showPicker];
        branchField.text=pickerDataSourceArray[[picker selectedRowInComponent:0]];
}

/**
 *  点击用户协议Button
 *
 *  @param btn UIButton
 */
-(void)tapGestureForServiceBtn:(UITapGestureRecognizer *)recognizer{
//    [Alert showAlert:@"点击用户协议Button"];
    
}
/**
 *  点击isReadBtn
 *
 *  @param btn UIButton
 */
-(void)tapGestureForReadBtn:(UITapGestureRecognizer *)recognizer{
//    [Alert showAlert:@"点击isReadBtn"];
    
}
#pragma mark - picker animation

-(void)showPicker{
//    [Alert showAlert:@"显示Picker!"];
    
//    self.bcgView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
//    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;   // 获得根窗口
    [self.view addSubview:self.bcgView];
    [self.view  addSubview:picker];

    /*
    pickerBottomConstraint.constant=0;

    [UIView animateWithDuration:0.25 animations:^{
            picker.alpha=1;
        [self.view setNeedsLayout];
    }];
     */
}

-(void)hidePicker{
//    [self.bcgView setFrame:CGRectMake(-1000, 0, self.view.frame.size.width , self.view.frame.size.height)];
    [self.bcgView removeFromSuperview];
    [picker removeFromSuperview];
    /*
    pickerBottomConstraint.constant=300;

    [UIView animateWithDuration:0.25 animations:^{
        picker.alpha=0;
        [self.view setNeedsLayout];
    }];
     */
}
#pragma mark - regist Button 
-(void)registButton:(UIButton *)button{
/*
    type=register&userName=ping&passwd=123465&email=232@qq.com&institute=010&branch=（utf-8编码）&byb=1&sfz=12134443&branchNum=200113
 */
    if (!_isRead) {
        [Alert showAlert:@"需要同意注册协议!"];
        return;
    }
    
    UITextField *pwdField = self.TextFieldArray[7];
    if ([pwdField text] != nil && [[pwdField text] length]!= 0) {
        
        if ([[pwdField text] length] < 6) {
            [Utils alertTitle:@"提示" message:@"用户密码小于6位！" delegate:nil cancelBtn:@"取消" otherBtnName:nil];
        }
    }else if([pwdField text] == nil){
        [Alert showAlert:@"密码为空!"];
        return;
    }
    
    UITextField *pwdCField =self.TextFieldArray[8];
    if (!([pwdCField.text isEqualToString:pwdCField.text])){
        [Alert showAlert:@"密码不一致"];
        return;
    }
    
    UITextField *userNameField = self.TextFieldArray[0];
    /**/
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet
    characterSetWithCharactersInString:@"0123456789QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm"] invertedSet];
    NSRange foundRange = [userNameField.text rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        [Alert showAlert:@"昵称只能包含数字和字母"];
        return ;
    }
    if(userNameField.text == nil ){
        [Alert showAlert:@"昵称为空!"];
        return;
    }
    

    UITextField *mailField = self.TextFieldArray[1];
    /**/
    if ([mailField text] != nil && [[mailField text] length]!= 0) {
        
        if (![Utils isValidateEmail:mailField.text]) {
            
            [Utils alertTitle:@"提示" message:@"邮箱格式不正确" delegate:nil cancelBtn:@"取消" otherBtnName:nil];
            return;
        }
    }else if([mailField text] == nil){
        [Alert showAlert:@"邮箱为空!"];
        return;
    }
    
    UITextField *sfzField  = self.TextFieldArray[2];
    /**/
    BOOL result = [self identifyNumCheck:sfzField.text];
    if (!result) {
        return;
    }
    UITextField *instituteField =self.TextFieldArray[4];
    NSString *institute;
    for (NSDictionary *dic  in unitInfoArray){
        if ([dic[@"partyName"] isEqualToString:instituteField.text]){
            institute=dic[@"partyNo"];
        }
    }
    
    UITextField *jobField = self.TextFieldArray[5];
    NSInteger byb=[self getJobNum:jobField.text];
    
    UITextField *branchF = self.TextFieldArray[6];
    NSString *branchNum;
    for (NSDictionary *dic  in branchInfoArray){
        if ([dic[@"partyName"] isEqualToString:branchF.text]){
            branchNum=dic[@"partyNo"];
        }
    }
    
    NSDictionary *requestData = @{@"type":@"register"
                                  ,@"userName":userNameField.text
                                  ,@"email":mailField.text
                                  ,@"sfz":sfzField.text
                                  ,@"institute":institute
                                  ,@"byb":[NSString stringWithFormat:@"%d",byb]
                                  ,@"branch":branchF.text
                                  ,@"passwd":pwdField.text
                                  ,@"branchNum":branchNum};
    
    [NetworkCenter AFRequestWithData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:Nil];
        NSLog(@"%@",dic);
        if ([dic[@"result"] isEqualToString:@"success"]) {
            [Alert showAlert:[NSString stringWithFormat:@"%@",dic[@"result"]]];
        }else if([dic[@"result"] isEqualToString:@"fail"]) {
            [Alert showAlert:[NSString stringWithFormat:@"%@",dic[@"cause"]]];
        }
        [self.navigationController popViewControllerAnimated:YES];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:[NSString stringWithFormat:@"error:%@",error.localizedDescription ]];
    }];
}

-(void)requestBranchDataSource{
#pragma mark 请求支部
    
    //@查找institute
    NSString *institute;
    for(NSDictionary *dic in unitInfoArray){
        if ([dic[@"partyName"] isEqualToString:unitField.text]){
            institute=dic[@"partyNo"];
        }
    }
    
    NSInteger byb;
    if ([jobField.text isEqualToString:@"本科生"]){
        byb=1;
    }
    else if ([jobField.text isEqualToString:@"研究生"]){
        byb=2;
    }
    else if ([jobField.text isEqualToString:@"博士"]){
        byb=3;
    }
    else if ([jobField.text isEqualToString:@"教师"]){
        byb=4;
    }
    else byb=0;
    
    NSDictionary *requestDic = @{@"type":@"getBranch",@"institute":institute,@"byb":[NSString stringWithFormat:@"%d",byb]};
    
    
    [NetworkCenter AFRequestWithData:requestDic SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSArray *arr=  [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        branchInfoArray=arr;
        
        if (arr.count<=0) {
            [Alert showAlert:@"信息为空!"];
            return;
        }
        NSMutableArray *mut = [[NSMutableArray alloc]init];
       
        for (NSDictionary *dic in branchInfoArray){
            [mut addObject:dic[@"partyName"]];
        }
        branchDataSource=[[NSArray alloc]initWithArray:mut];
        branchEnable=YES;
//        [picker reloadAllComponents];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark - 根据字符串获取职位编码
-(NSInteger)getJobNum:(NSString*)string{
    NSInteger byb;
    if ([string isEqualToString:@"本科生"]){
        byb=1;
    }
    else if ([string isEqualToString:@"研究生"]){
        byb=2;
    }
    else if ([string isEqualToString:@"博士"]){
        byb=3;
    }
    else if ([string isEqualToString:@"教师"]){
        byb=4;
    }
    else byb=0;
    return byb;
}

-(BOOL)identifyNumCheck:(NSString*) identifyNum{
    if (identifyNum.length == 15 || identifyNum.length == 18) {
        NSString *emailRegex = @"^[0-9]*$";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        bool sfzNo = [emailTest evaluateWithObject:[identifyNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
        
        if (identifyNum.length == 15) {
            if (!sfzNo) {
//                [self HUDShow:@"请输入正确的身份证号" delay:1.5];
                [Alert showAlert:@"身份证号格式有误"];
                return NO;
            }
        }else if (identifyNum.length == 18) {
            bool sfz18NO = [self checkIdentityCardNo:identifyNum];
            if (!sfz18NO) {
//                [self HUDShow:@"请输入正确的身份证号" delay:1.5];
                [Alert showAlert:@"身份证号格式有误"];
                return NO;
            }
       }
        return YES;
    }else{
        [Alert showAlert:@"身份证号格式有误"];
        return NO;
    }
}

#pragma mark - 身份证识别
-(BOOL)checkIdentityCardNo:(NSString*)cardNo
{
    if (cardNo.length != 18) {
        return  NO;
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
    }
    
    return  NO;
}


@end
